package com.ruoyi.opencv.service.impl;

import com.ruoyi.files.domain.SysFileManage;
import com.ruoyi.files.service.ISysFilesManageService;
import com.ruoyi.opencv.domain.ScanMask;
import com.ruoyi.opencv.service.IServerScanService;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.nio.file.Paths;
import java.util.Collections;

import static com.ruoyi.opencv.utils.OpenCVTool.*;
import static org.opencv.imgcodecs.Imgcodecs.imread;
import static org.opencv.imgcodecs.Imgcodecs.imwrite;

@Service
public class ServerScanService implements IServerScanService {


    static {
        // 加载 OpenCV 库
        URL url = ClassLoader.getSystemResource("lib/opencv/opencv_java4110.dll");
        System.load(url.getPath());
    }

    @Override
    public MatOfPoint getMask(Mat rawImage) {
        Mat balancedImage, enhancedImage, whiteMask;
        try {
            // Step 1: 全局白色平衡
            balancedImage = whiteBalance(rawImage);

            // Step 2: 增强亮白色
            enhancedImage = enhanceBrightWhite(balancedImage, 200);

            // Step 3: Lab空间提取白色区域
            whiteMask = extractWhiteRegionUsingLab(balancedImage);

            // Step 4: 去噪&修补
            whiteMask = deNoiseFix(whiteMask);

            // Step 5: 寻找四边形的角点
            MatOfPoint bestContour = findQuadrilateral(rawImage, whiteMask);

            // Step 6: 返回轮廓
            return bestContour;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
